import React, { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import './index.css'
import { Avatar, Button,Row,Col,Input ,Form} from 'antd'
import { LeftOutlined,SendOutlined ,SmileOutlined} from '@ant-design/icons';
import { GetMessageRouter, AddMessageRouter, host } from '../../api'
import { io } from 'socket.io-client'
import Picker from "emoji-picker-react";
import axios from 'axios';
export default function Conversation() {
  const msgInput = React.useRef()
  const msglist=React.useRef()
  const params = useParams();
  const [messageList, setMessageList] = useState([])
  const user_acc = localStorage.getItem('login-user')
  const user_avatar=localStorage.getItem('user-avatar')
  const navigate = useNavigate();
  const [socket, setSocket] = useState(undefined)
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  //未登录重定向
  React.useEffect(() => {
    if (!localStorage.getItem('login-user')) {
      navigate(`/login`)
    }
    else {
      axios({
        method: 'get',
        url: GetMessageRouter,
        params: {
          f_acc: params.f_acc,
          u_acc: user_acc
        },
      }).then(result => {
        // console.log(result.data);
        setMessageList(result.data)
      }).finally(()=>{ msglist.current.scrollTop=msglist.current.scrollHeight;})
    }
  }, [])// eslint-disable-line
  //连接socket
  React.useEffect(() => {
    setSocket(io(host))
  }, [])// eslint-disable-line
  React.useEffect(() => {
    if (socket) {
      socket.emit("add-user", user_acc);
    }
  }, [socket])
  const handleEmojiPickerhideShow = () => {
    setShowEmojiPicker(!showEmojiPicker);
  };
React.useEffect(()=>{
  msglist.current.scrollTop=msglist.current.scrollHeight;
})
  //发送信息
  const sendMessage = async (values) => {
    //发送消息
    if(values.message){
    await axios({
      url: AddMessageRouter,
      method: 'post',
      data: {
        content: values.message,
        sender: user_acc,
        receiver: params.f_acc,
        date: new Date()
      }
    }).then((res)=>{
      // console.log(res.data.message);
    }).catch((err) => {
      console.log('错误'+err);
    })
    }
    await axios({
      method: 'get',
      url: GetMessageRouter,
      params: {
        f_acc: params.f_acc,
        u_acc: user_acc
      },
    }).then(result => {
      setMessageList(result.data)
    })
    socket.emit('send-message', {
      msg: values.message,
      from: user_acc,
      to: params.f_acc
    });
   
    msgInput.current.setFieldsValue({
      message:''
    })
  }

  const back=()=>{
    navigate(-1)
  }
  const toInfo=(acc)=>{
    navigate(`/userinfo/${acc}`)
  }
  //socket收到消息
  React.useEffect(() => {
    if (socket) {
      socket.on('receiver-message', msg => {
        console.log('收到消息' + msg);
        axios({
          method: 'get',
          url: GetMessageRouter,
          params: {
            f_acc: params.f_acc,
            u_acc: user_acc
          },
        }).then(result => {
          // console.log(result.data);
          setMessageList(result.data)
        
        })
      })
    }
  })// eslint-disable-line


  const setSendTime=(time)=>{
    const T=new Date(time)
    return T.toLocaleTimeString()
  }
  //点击emoji
  const handleEmojiClick = (event, emojiObject) => {
    msgInput.current.setFieldsValue({
      message:msgInput.current.getFieldValue('message')+emojiObject.emoji
    })
    setShowEmojiPicker(!showEmojiPicker);
  };


  // console.log(params);
  let con = messageList.map(i => (
  <div className='msg_box'  key={i.id}>
    <span className={i.sender === user_acc ? ' send_time_r' : ' send_time_l'}>{ setSendTime(i.date)}</span>
  <Avatar  size='large' src={i.sender === user_acc ? `http://www.ayaka002.top/assets/avatar/${user_avatar}.png ` : ''} 
   className={i.sender === user_acc ? 'con_right' : 'display_none'}></Avatar>
  <Avatar  onClick={()=>toInfo(params.f_acc)} size="large" src={i.sender === user_acc ? '' :`http://www.ayaka002.top/assets/avatar/${params.f_avatar}.png`}
    className={i.sender === user_acc ? 'display_none' : 'con_left'}></Avatar>
  <li className={i.sender === user_acc ? 'con_right msglistitem' : 'con_left msglistitem'}>
    {i.content}
  </li>
 
  </div>))
  return (
    <div>
      <div className='header'>
      <Row align='middle' style={{height:"50px"}}>
      <Col span={8}><Button style={{color:'#fff',border:'none'}} onClick={back} type='ghost' shape='circle' icon={<LeftOutlined />}></Button> </Col>
      <Col span={8} style={{textAlign:"center",fontSize:"16px",fontWeight:"bold",color:"#fff"}}>{params.f_name}</Col>
    </Row>
      </div>
      <div className='msglist' ref={msglist}>
        {con}
      </div>
      <div className="sendmsg">
      <Form 
      ref={msgInput}
        wrapperCol={{
          span:4
        }
        }
      layout='inline'
      name="basic"
      onFinish={sendMessage}
    >
      <Form.Item
>

{/* 
<EmojiReact 
reactions={[]}
onEmojiClick={onEmojiClick}/> */}
<Button type='ghost'shape='circle' style={{marginLeft:"10px"}}   onClick={handleEmojiPickerhideShow} icon={<SmileOutlined />}></Button>
{showEmojiPicker && <Picker  onEmojiClick={handleEmojiClick}/>}
    </Form.Item>
      <Form.Item  
       wrapperCol={{
        span:12
      }
      }
      name='message' 

      >
      <Input
     
      showCount
      
      maxLength="50"
      style={{borderRadius:"15px"}}
  /> 
      </Form.Item>
      <Form.Item
    >
       <Button type='primary'shape='circle' htmlType="submit" icon={<SendOutlined />}></Button>
      </Form.Item>
    </Form>
      </div>
    </div>
  )
}
